<script lang="ts" setup>
import Selector from "@/components/Selector.vue";
import Inputter from "@/components/Inputter.vue";
import { reactive, ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import Password from "@/components/Password.vue";
import { useAdminStore } from "@/stores/admin";
import router from "@/router/router";
import instance from '@/utils/request';

/*
    已废弃
*/

// 管理员新建用户页面
const admin = useAdminStore();

let user_id = ref("");
let user_name = ref("");
let user_password = ref("");
let user_password_again = ref("");
let customer_id = ref("");
let customer_name = ref("");
let customer_phone = ref("");
let customer_sex = ref("");

// 性别的下拉框（表单）
const customer_sex_form_options = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
]

interface RuleForm {
  user_id: string
  user_name: string
  user_password: string
  user_password_again: string
  customer_id: string
  customer_name: string
  customer_phone: string
  customer_sex: string
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  user_id: '',
  user_name: '',
  user_password: '',
  user_password_again: '',
  customer_id: '',
  customer_name: '',
  customer_phone: '',
  customer_sex: ''
});

// 确认密码验证
const password1 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空！'));
  }
  else {
    if (ruleForm.user_password_again !== '') {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField('user_password_again');
    }
    callback();
  }
}
const password2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('两次密码不一致！'));
  }
  else if (value !== ruleForm.user_password) {
    callback(new Error('两次密码不一致！'));
  }
  else {
    callback();
  }
}

const rules = reactive<FormRules<RuleForm>>({
  user_id: [
    { required: true, message: 'uid不能为空！', trigger: 'blur' }
  ],
  user_name: [
    { required: true, message: '账号名不能为空！', trigger: 'blur' },
    { min: 1, max: 8, message: '1-8个字符', trigger: 'blur'}
  ],
  user_password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { validator: password1, trigger:'blur' }
  ],
  user_password_again: [
    { required: true, message: '两次密码不一致！', trigger: 'blur' },
    { validator: password2, trigger:'blur' }
  ],
  customer_id: [
    { min: 18, max:18, message: '请输入正确的身份证号！', trigger: 'blur' }
  ],
  customer_phone: [
    { min: 11, max:11, message: '请输入正确的电话号码！', trigger: 'blur' }
  ]
});

const submitForm =  (formEl: FormInstance | undefined) => {
  // 提交表单
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      add();
    }
  });
}

function add() {
  // 新建用户
  instance.request({
    url: 'admin/usermanage/newuser/add',
    method: 'POST',
    data: {
      user_id: ruleForm.user_id,
      user_name: ruleForm.user_name,
      user_password: ruleForm.user_password,
      customer_id: ruleForm.customer_id,
      customer_name: ruleForm.customer_name,
      customer_phone: ruleForm.customer_phone,
      customer_sex: ruleForm.customer_sex
    },
    headers: {
      "Admin-Id": admin.admin_id,
      "Admin-Password": admin.admin_password
    }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "新建失败！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_user_id") {
          ElMessage({
            message: "uid已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "ERROR_user_name") {
          ElMessage({
            message: "账号名已被使用！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          ElMessage({
            message: "新建成功！",
            type: "success"
          });
        }
      })
      .catch(function(error){
        console.log(error);
        if(error.response.request.status === 401) {
          ElMessage({
            message: "无权限！",
            type: "error"
          });
          admin.logout();
          router.push("/admin/index");
          return;
        }
        ElMessage({
          message: "新建失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <div class="new">
    <el-form
        label-width="12vh"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
    >
      <el-form-item label="uid：" prop="user_id">
        <inputter width="200" v-model="ruleForm.user_id"/>
      </el-form-item>

      <el-form-item label="账号名：" prop="user_name">
        <inputter width="200" v-model="ruleForm.user_name"/>
      </el-form-item>

      <el-form-item label="密码：" prop="user_password">
        <password width="200" v-model="ruleForm.user_password"/>
      </el-form-item>

      <el-form-item label="确认密码：" prop="user_password_again">
        <password width="200" v-model="ruleForm.user_password_again"/>
      </el-form-item>

      <el-form-item label="身份证号：" prop="customer_id">
        <inputter width="200" v-model="ruleForm.customer_id"/>
      </el-form-item>

      <el-form-item label="姓名：" prop="customer_name">
        <inputter width="200" v-model="ruleForm.customer_name"/>
      </el-form-item>

      <el-form-item label="电话号码：" prop="customer_phone">
        <inputter width="200" v-model="ruleForm.customer_phone"/>
      </el-form-item>

      <el-form-item label="性别：" prop="customer_sex">
        <selector width="200" :options="customer_sex_form_options" v-model="ruleForm.customer_sex"/>
      </el-form-item>

      <el-button color="#568fc1" class="button-color button-width"
                 @click="submitForm(ruleFormRef)">
        <span>新建</span>
      </el-button>
    </el-form>
  </div>
</template>

<style scoped>
.new {
  margin: 10vh;
  height: 50vh;
  /* border: 1px solid black; */
}
.button-color {
  --el-button-hover-bg-color: rgb(238, 244, 249) !important;
  --el-button-hover-text-color: #568fc1 !important;
  --el-button-text-color: white !important;
}
.button-width {
  margin-left: 4vh;
  width: 250px;
}
</style>